package com.company.project.action;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.company.project.bean.Gbook;
import com.company.project.dao.GbookDao;

@Controller
public class GbookAction {
	
	@Autowired
	private GbookDao gbookDao;
	
	
	@RequestMapping("/list.do")
	public ModelAndView list(){
		List<Gbook> list = gbookDao.findAll();
		System.out.println(list.size());
		ModelAndView view = new ModelAndView();
		view.addObject("gbook", list);	
		return view;
	}
	
	@RequestMapping("/page.do")
	public ModelAndView list(@RequestParam("p") int p){
		List<Gbook> list = gbookDao.selectPage((p-1)*3, 3);
		ModelAndView view = new ModelAndView();
		view.addObject("gbook", list);
		view.setViewName("list");
		return view;
	}
	
	@RequestMapping("/save.do")
	public String save(@RequestParam("username") String username,@RequestParam("title") String title,@RequestParam("content") String content,@RequestParam("age") int age){
		Gbook gbook = new Gbook();
		gbook.setUsername(username);
		gbook.setTitle(title);
		gbook.setContent(content);
		gbook.setAge(age);
		gbookDao.insert(gbook);
		return "redirect:/list.do";
	}
	
	@RequestMapping("/delete.do")
	public String delete(@RequestParam("id") int id){
		gbookDao.delete(id);
		return "redirect:/list.do";
	}
	
	@RequestMapping("/findid.do")
	public ModelAndView findById(@RequestParam("id") int id){
		ModelAndView view = new ModelAndView();
		Gbook gbook = gbookDao.fingById(id);
		view.addObject("gbook",gbook);
		view.setViewName("find");
		return view;
	}
	
	@RequestMapping("/findname.do")
	public ModelAndView findByName(@RequestParam("username") String username){
		ModelAndView view = new ModelAndView();
		Gbook gbook = gbookDao.fingByUsername(username);
		view.addObject("gbook",gbook);
		view.setViewName("find");
		return view;
	}
}
